//
//  CustomPlayer.m
//  RoadshowTreasure
//
//  Created by YangLiang on 2016/10/17.
//  Copyright © 2016年 Adinnet. All rights reserved.
//

#import "CustomPlayer.h"

@interface CustomPlayer ()
//播放器相关
@property (nonatomic, strong) AVPlayerItem *songItem;
//播放进度观察者
@property (nonatomic, strong) id playTimeObserver;
//总时间
@property (nonatomic, strong) NSString *allTime;


@end

@implementation CustomPlayer

#pragma mark - 单例
+ (id)sharedInstance {
    static CustomPlayer *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[CustomPlayer alloc] init];
    });
    return manager;
}

#pragma mark - 播放
- (void)sourcePlay {
    if (_sourcePlayer) {
        [_sourcePlayer play];
    }
}

#pragma mark - 暂停
- (void)sourceStop {
    if (_sourcePlayer) {
        [_sourcePlayer pause];
    }
}

#pragma mark - 设置播放时间
- (void)playToTimeWith:(CMTime)time withInteger:(NSInteger)value {
    [_songItem seekToTime:time];
    
    if (_customPlayerShowBlock) {
        _customPlayerShowBlock([NSString stringWithFormat:@"%ld",value],_allTime);
    }
}

#pragma mark - 设置音频播放器
- (void)setCustomPlayerStr:(NSString *)customPlayerStr {
    NSURL *url = [NSURL URLWithString:customPlayerStr];
    _songItem = [[AVPlayerItem alloc] initWithURL:url];
    _sourcePlayer = [[AVPlayer alloc] initWithPlayerItem:_songItem];
    
    //监听播放状态
    __weak CustomPlayer *weakSelf = self;
    _playTimeObserver = [_sourcePlayer addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        float current = CMTimeGetSeconds(time);
        if (current) {
            [weakSelf updateVideoSlider:current];
        }
    }];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    //播放完成
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:_songItem];
    //监听改播放器状态
    [_songItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
}

#pragma mark - 监听改播放器状态
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void *)context {
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerItem *item = (AVPlayerItem *)object;
        
        switch (_sourcePlayer.status) {
            case AVPlayerStatusUnknown:
                NSLog(@"未知状态，此时不能播放");
                if (_customPlayerIsShowPlayView) {
                    _customPlayerIsShowPlayView(NO);
                }
                break;
            case AVPlayerStatusReadyToPlay:
                NSLog(@"准备完毕，可以播放");
                if (_customPlayerIsShowPlayView) {
                    _customPlayerIsShowPlayView(YES);
                }
                //获取视频总长度
                CMTime duration = item.duration;
                [self setMaxDuratuin:CMTimeGetSeconds(duration)];
                
                break;
            case AVPlayerStatusFailed:
                NSLog(@"加载失败，网络或者服务器出现问题");
                if (_customPlayerIsShowPlayView) {
                    _customPlayerIsShowPlayView(NO);
                }
                break;
            default:
                break;
        }
    }
}

#pragma mark - 播放完成
- (void)playbackFinished:(NSNotification *)notice {
    [_songItem seekToTime:kCMTimeZero];
    
    if (_customPlayerShowFinish) {
        _customPlayerShowFinish(_allTime);
    }
}

#pragma mark - 计算当前在第几秒
- (void)updateVideoSlider:(float)currentTime {
    NSString *playTime = [NSString stringWithFormat:@"%.f",currentTime];

    if (_customPlayerShowBlock) {
        _customPlayerShowBlock(playTime,_allTime);
    }
}

#pragma mark - 获取视频总长度
- (void)setMaxDuratuin:(float)duration {
    NSString *playDuration = [NSString stringWithFormat:@"%.f",duration];
    NSInteger twoMin = [playDuration integerValue]/60;
    NSInteger twoSec = [playDuration integerValue]%60;
    
    _allTime = [NSString stringWithFormat:@"%.2ld:%.2ld",twoMin,twoSec];
    if (_customPlayerShowTime) {
        _customPlayerShowTime(playDuration);
    }
}

#pragma mark - 移除通知 & KVO
- (void)removeObserverAndNotification {
    [_sourcePlayer replaceCurrentItemWithPlayerItem:nil];
    [_songItem removeObserver:self forKeyPath:@"status"];
    [_sourcePlayer removeTimeObserver:_playTimeObserver];
    _playTimeObserver = nil;

    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
}


@end
